package com.isoft.c2team3service2.controller;

import com.isoft.c2team3service2.bean.ResponseData;
import com.isoft.c2team3service2.dto.PostDTO;
import com.isoft.c2team3service2.entity.Post;
import com.isoft.c2team3service2.entity.UserDTO;
import com.isoft.c2team3service2.service.PostService;
import com.isoft.c2team3service2.service.UserPaidPostService;
import com.isoft.c2team3service2.util.UserHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 帖子控制器
 */
@RestController
@RequestMapping("/posts")
public class PostController extends BaseController {
    // 添加日志记录器
    private static final Logger log = LoggerFactory.getLogger(PostController.class);
    @Autowired
    private UserPaidPostService userPaidPostService;
    @Autowired
    private PostService postService;

    /**
     * 创建新帖子（返回包含isPaid、isPrivate、price的帖子信息）
     */
    @PostMapping
    public ResponseData<PostDTO> createPost(
            @RequestParam(value = "file", required = false) MultipartFile file,
            @RequestParam("title") String title,
            @RequestParam("content") String content,
            // 新增：接收前端传递的isPaid（默认0，允许传递1）
            @RequestParam(value = "isPaid", defaultValue = "0") Integer isPaid,
            // 新增：接收前端传递的isPrivate（默认0，允许传递1）
            @RequestParam(value = "isPrivate", defaultValue = "0") Integer isPrivate,
            // 新增：接收前端传递的price（非必填，默认null）
            @RequestParam(value = "price", required = false) BigDecimal price
    ) {
        // 调用服务层创建帖子（使用接收的参数，而非硬编码默认值）
        boolean success = postService.createPost(file, title, content, isPaid, isPrivate, price);
        if (success) {
            // 创建成功后，查询用户的所有帖子并取最新的一个
            Integer userId = UserHolder.getUser().getId();
            List<PostDTO> userPosts = postService.findByUserId(userId);
            PostDTO createdPost = userPosts.isEmpty() ? null : userPosts.get(0);
            return resultT(createdPost, "创建帖子");
        } else {
            return resultT(null, "创建帖子（可能因付费/私密状态冲突或价格无效）");
        }
    }

    /**
     * 根据ID查询帖子
     */
    @GetMapping("/{id}")
    public ResponseData<Post> getPostById(@PathVariable Integer id) {
        Post post = postService.findById(id);
        return resultT(post, "查询帖子");
    }

    /**
     * 查询用户的所有帖子
     */
    @GetMapping("/user")
    public ResponseData<List<PostDTO>> getUserPosts() {
        UserDTO user = UserHolder.getUser();
        List<PostDTO> posts = postService.findByUserId(user.getId());
        return resultT(posts, "查询用户帖子");
    }

    /**
     * 查询热门帖子
     */
    @GetMapping("/hot")
    public ResponseData<List<PostDTO>> getHotPosts(@RequestParam(defaultValue = "10") int limit) {
        List<PostDTO> posts = postService.findHotPosts(limit);
        return resultT(posts, "查询热门帖子");
    }

    /**
     * 查询最新帖子
     */
    @GetMapping("/latest")
    public ResponseData<List<PostDTO>> getLatestPosts(@RequestParam(defaultValue = "10") int limit) {
        List<PostDTO> posts = postService.findLatestPosts(limit);
        return resultT(posts, "查询最新帖子");
    }

    /**
     * 更新帖子
     */
    @PutMapping("/{id}")
    public ResponseData<Boolean> updatePost(@PathVariable Integer id,
                                            @RequestBody Post post ,
                                            @RequestParam(required = false)MultipartFile  file) {
        post.setId(id);
        boolean success = postService.updatePost(post,file);
        return resultBoolean(success, "更新帖子");
    }


    /**
     * 点赞帖子
     */
    @PostMapping("/{id}/like")
    public ResponseData<Boolean> likePost(@PathVariable Integer id) {
        boolean success = postService.likePost(id);
        return resultBoolean(success, "点赞帖子");
    }

    //TODO 测试查询是否点赞，以及测试点赞插入user_like表，取消点赞删除user_like中的数据

    /**
     * 查询是否已经被用户点赞
     */
    @GetMapping("/{id}/like")
    public ResponseData<Boolean> checkLikeStatus(@PathVariable Integer id) {
        boolean isLiked = postService.checkLikeStatus(id);
        return resultBoolean(isLiked, "查询是否被用户点赞");
    }


    /**
     * 取消点赞帖子
     */
    @DeleteMapping("/{id}/like")
    public ResponseData<Boolean> unlikePost(@PathVariable Integer id) {
        boolean success = postService.unlikePost(id);
        return resultBoolean(success, "取消点赞帖子");
    }

    /**
     * 浏览帖子
     */
    @PostMapping("/{id}/view")
    public ResponseData<Boolean> increaseViewCount(@PathVariable Integer id) {
        boolean success = postService.increaseViewCount(id);
        return resultBoolean(success, "浏览帖子");
    }
    /**
     * 设置帖子私密状态
     * @param id 帖子ID
     * @param isPrivate 私密状态（1=私密，0=公开），必须传递且只能是0或1
     */
    @PutMapping("/{id}/private")
    public ResponseData<Boolean> setPostPrivate(
            @PathVariable Integer id,
            // 强制要求传递参数，且无默认值，避免null
            @RequestParam(required = true) Integer isPrivate) {

        // 1. 非空校验（虽然required=true已保证，但做二次防御）
        if (isPrivate == null) {
            return resultBoolean(false, "请传递私密状态参数（0=公开，1=私密）");
        }

        // 2. 合法性校验
        if (isPrivate != 0 && isPrivate != 1) {
            return resultBoolean(false, "私密状态值无效（0=公开，1=私密）");
        }

        UserDTO user = UserHolder.getUser();
        boolean success = postService.setPostPrivate(id, user.getId(), isPrivate);
        return resultBoolean(success, isPrivate == 1 ? "设置帖子为私密" : "设置帖子为公开");
    }

    /**
     * 查询用户的所有私密帖子
     * 仅当前登录用户可查询自己的私密帖子
     */
    @GetMapping("/user/private")
    public ResponseData<List<Post>> getUserPrivatePosts() {
        // 获取当前登录用户信息
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            // 未登录时，返回空列表和错误信息（保持返回类型为List<Post>）
            return resultT(null, "请先登录");
        }
        // 调用服务层查询当前用户的私密帖子
        List<Post> privatePosts = postService.findPrivatePostsByUserId(user.getId());
        return resultT(privatePosts, "查询用户私密帖子");
    }

    /**
     * 物理删除帖子（仅作者可删除）
     * @param id 要删除的帖子ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    public ResponseData<Boolean> deletePost(@PathVariable Integer id) {
        // 1. 校验用户是否登录
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return resultBoolean(false, "请先登录");
        }

        // 2. 调用服务层执行物理删除（传入帖子ID和当前用户ID）
        boolean success = postService.deletePost(id, user.getId());
        return resultBoolean(success, success ? "删除" : "删除（无权限或帖子不存在）");
    }

    /**
     * 购买付费帖子
     */
    @PostMapping("/{postId}/purchase")
    public ResponseData<Boolean> purchasePost(@PathVariable Integer postId) {
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return resultBoolean(false, "请先登录");
        }

        boolean success = userPaidPostService.purchasePost(user.getId(), postId);
        // 添加日志记录
        log.info("用户{}购买帖子{}的结果：{}", user.getId(), postId, success);
        return resultBoolean(success, success ? "购买" : "购买失败（帖子不存在或已购买）");
    }

    /**
     * 检查当前用户是否已购买帖子
     */
    @GetMapping("/{postId}/check-paid")
    public ResponseData<Boolean> checkPaidStatus(@PathVariable Integer postId) {
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return resultBoolean(false, "请先登录");
        }

        boolean hasPaid = userPaidPostService.hasPaid(user.getId(), postId);

        return resultBoolean(hasPaid, hasPaid ? "已购买" : "未购买");
    }

    /**
     * 设置帖子为付费内容
     * @param postId 帖子ID
     * @param isPaid 是否付费
     * @param price 价格
     * @return 设置结果
     */
    @PutMapping("/{postId}/paid")
    public ResponseData<Boolean> setPostPaid(
            @PathVariable Integer postId,
            @RequestParam(required = true) Boolean isPaid,
            @RequestParam(required = false) BigDecimal price) {

        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return resultBoolean(false, "请先登录");
        }

        // 验证价格（如果设置为付费帖子，价格必须大于0）
        if (isPaid && (price == null || price.compareTo(BigDecimal.ZERO) <= 0)) {
            return resultBoolean(false, "付费帖子价格必须大于0");
        }

        boolean success = postService.setPostPaid(postId, user.getId(), isPaid, price);
        return resultBoolean(success, success ? "设置成功" : "设置失败（帖子不存在或无权限）");
    }

    /**
     * 查询公开的付费帖子（排除私密帖）
     * @param limit 最多返回的帖子数量，默认10条
     * @return 付费帖子列表
     */
    @GetMapping("/paid")
    public ResponseData<List<Post>> getPaidPosts(@RequestParam(defaultValue = "10") int limit) {
        // 调用服务层查询公开的付费帖子
        List<Post> paidPosts = postService.findPublicPaidPosts(limit);
        return resultT(paidPosts, "查询付费帖子");
    }
    /**
     * 新增：创建帖子并提及艺人（支持上传图片）
     * @param artistNames 提及的艺人名称（逗号分隔，如"周杰伦,林俊杰"）
     */
    @PostMapping("/create-with-artist")
    public ResponseData<Boolean> createPostWithArtist(
            @RequestParam(value = "file", required = false) MultipartFile file,
            @RequestParam("title") String title,
            @RequestParam("content") String content,
            @RequestParam(value = "isPaid", defaultValue = "0") Integer isPaid,
            @RequestParam(value = "isPrivate", defaultValue = "0") Integer isPrivate,
            @RequestParam(value = "price", required = false) BigDecimal price,
            @RequestParam(value = "artistNames", defaultValue = "") String artistNames) {

        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return resultT(false, "请先登录");
        }

        boolean success = postService.createPostWithArtistTags(
                file, title, content, isPaid, isPrivate, price, artistNames
        );

        return success ? resultT(true, "创建帖子（提及艺人）") : resultT(false, "创建帖子（提及艺人）");
    }

    /**
     * 新增：按艺人名称模糊查询提及该艺人的公开帖子
     * @param artistName 艺人名称（如"周"，支持模糊匹配）
     * @param limit 最大返回数量（默认10）
     */
    @GetMapping("/search-by-artist")
    public ResponseData<List<PostDTO>> searchPostsByArtist(
            @RequestParam("artistName") String artistName,
            @RequestParam(value = "limit", defaultValue = "10") int limit) {
        List<PostDTO> posts = postService.findPostsByArtistNameLike(artistName, limit);
        return resultT(posts, "查询提及艺人[" + artistName + "]的帖子");
    }

    /**
     * 有条件的查询帖子,首页
     * @param content 搜索内容（支持模糊匹配）
     */
    @GetMapping("/vagueSearch")
    public ResponseData<List<PostDTO>> searchPosts(String content){
        List<PostDTO> posts = postService.searchPosts(content);
//        return resultT(posts, "查询帖子");
        return posts.isEmpty() ? resultT(new ArrayList<>(), "查询帖子") : resultT(posts, "查询帖子");
    }
}